import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';

@Injectable()
export class PostService {
  constructor(private readonly prisma: PrismaService) {}

  async findAll() {
    return await this.prisma.post.findMany({
      include: {
        tags: true,
        author: true,
      },
      orderBy: { createdAt: 'desc' },
    });
  }

  async findOneBySlug(slug: string) {
    return await this.prisma.post.findUnique({
      where: { slug },
      include: {
        tags: true,
        author: true,
      },
    });
  }

  async create(createPostDto: CreatePostDto) {
    const { tags, authorId, ...data } = createPostDto;
    return await this.prisma.post.create({
      data: {
        ...data,
        author: {
          connect: { id: authorId },
        },
        tags: tags
          ? {
              connect: tags.map((id) => ({ id })),
            }
          : undefined,
      },
      include: {
        tags: true,
        author: true,
      },
    });
  }

  async update(id: string, updatePostDto: UpdatePostDto) {
    const { tags, ...data } = updatePostDto;
    return await this.prisma.post.update({
      where: { id },
      data: {
        ...data,
        tags: tags
          ? {
              set: tags.map((id) => ({ id })),
            }
          : undefined,
      },
      include: {
        tags: true,
        author: true,
      },
    });
  }

  async remove(id: string) {
    return await this.prisma.post.delete({
      where: { id },
    });
  }
}
